package com.geek.novel.activity.book

import android.content.Intent
import android.os.Bundle
import android.os.Message
import android.text.TextUtils
import android.view.KeyEvent
import android.view.WindowManager
import com.geek.novel.R
import com.geek.novel.activity.base.BaseActivity
import com.geek.novel.common.Constant
import com.geek.novel.dialog.ConfirmDialog
import com.geek.novel.dialog.SectionIndexDialog
import com.geek.novel.dialog.ViewerMenuDialog
import com.geek.novel.entity.BookIndex
import com.geek.novel.entity.BookRead
import com.geek.novel.fragment.FragmentLightSetting
import com.geek.novel.network.RslHandler
import com.geek.novel.services.BookRepository
import com.geek.novel.services.CrawlerRepository
import com.geek.novel.services.NovelService
import com.geek.novel.ui.ReadView
import com.geek.novel.utils.LogCatUtil
import com.geek.novel.utils.SPUtil
import com.geek.novel.utils.ToastUtils
import com.geek.novel.view.loading.LoadingDialogUtil
import com.geek.novel.vo.ApiErrorResult
import com.geek.novel.vo.ApiResult
import com.geek.novel.vo.CrawlerSectionVo
import com.zackratos.ultimatebarx.ultimatebarx.addStatusBarTopPadding
import kotlinx.android.synthetic.main.activity_viewer.*


class ViewerActivity : BaseActivity(), RslHandler {
	
	var bookId: String? = null
	
	var book: BookRead? = null

	/**音量键点击翻页*/
	private var isVoicePage = false

	/**是否永不锁屏*/
	private var isLockScreenNever = false
	
	var bookIndexList = ArrayList<BookIndex>()

	/**文本控件*/
	private lateinit var sectionView: ReadView
	
	/**菜单的弹框*/
	private lateinit var bottomDialog: ViewerMenuDialog
	
	/**章节列表的弹框*/
	private lateinit var sectionIndexDialog: SectionIndexDialog

	/**小说接口*/
	private val bookService = BookRepository.getInstance()

	/**小说爬取接口*/
	private val crawlerRepository = CrawlerRepository.getInstance()

	/**确认框*/
	private lateinit var confirmDialog: ConfirmDialog

	/**小说服务*/
	lateinit var novelService: NovelService

	override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
		super.onActivityResult(requestCode, resultCode, data)
		bottomDialog.onActivityResult(requestCode, resultCode, data)
	}
	
	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_viewer)
		try {
			//初始化服务对象
			novelService = NovelService(this)

			//初始化控件
			this.initV()

			//初始化确认弹框
			this.initConfirmDialog()

			//填充布局
			this.inflateLayout()

			//初始化小说章节、阅读位置等等
			this.initSection()

			//书本的菜单
			this.initDialogMenu()

			//加载数据目录数据
			this.getBookIndex()

		} catch (e: Exception) {
			LogCatUtil.e("ViewerActivity", e.message, e)
			ToastUtils.toast(e.message)
			finish()
		}
	}

	/**初始化确认弹框*/
	private fun initConfirmDialog(){
		confirmDialog = ConfirmDialog(this@ViewerActivity)
		confirmDialog.hideDismissBtn()
		confirmDialog.setOnConfirmListener("更换书源") {
			confirmDialog.dismiss()
			val params = Bundle()
			params.putString("bookId", this.book!!.bookId)
			this.startActivityForResultByAnim(this, CrawlerSourceActivity::class.java, params, Constant.ACTIVITY_RESULT_CRAWLER_SOURCE)
		}
	}

	/**
	 * 加载数据目录数据
	 */
	private fun getBookIndex() {
		//开启线程爬取数据
		Thread{
			kotlin.run {
				crawlerRepository.startCrawlerBook(this.book!!, this, true)
			}
		}.start()
	}
	
	/**重新获取书籍列表信息*/
	fun reCrawlerBookIndex(){
		book = bookService.findBookByBookId(this.bookId)
		this.getBookIndex()
	}
	
	/**
	 * 初始化控件
	 */
	private fun initV() {
		ly_reader_container.addStatusBarTopPadding()

		//音量键点击翻页
		this.isVoicePage = this.getVoicePage()

		//是否永不锁屏
		this.isLockScreenNever = this.getLockScreenNever()
		setLockScreenNever(this.isLockScreenNever)//设置永不锁屏

		//调节系统亮度
		FragmentLightSetting.initCurrentSystemBright(this)

	}


	/**初始化弹框菜单*/
	private fun initDialogMenu(){
		//初始化弹框
		bottomDialog = ViewerMenuDialog(this, this.sectionView)
		bottomDialog.onCreateView()
		//初始化弹框
		sectionIndexDialog = SectionIndexDialog(this, this.sectionView)
		sectionIndexDialog.onCreateView()
	}

	/**设置音量键的翻页功能*/
	override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
		when(keyCode){
			KeyEvent.KEYCODE_VOLUME_UP -> {
				if(isVoicePage){
					this.sectionView.prevPage()
					return true
				}
			}
			KeyEvent.KEYCODE_VOLUME_DOWN -> {
				if(isVoicePage){
					this.sectionView.nextPage()
					return true
				}
			}
			KeyEvent.KEYCODE_BACK -> {
				//客户点了后退，先关闭菜单弹框，没有弹框再关闭页面
				if(sectionIndexDialog.isShowing()){
					sectionIndexDialog.close()
					return true
				}
				if(bottomDialog.isShowing()){
					bottomDialog.close()
					return true
				}
			}
		}
		return super.onKeyDown(keyCode, event)
	}


	/**
	 * 初始化小说章节、阅读位置等等
	 */
	private fun initSection(){
		val bundle = intent.extras?:Bundle()
		try {
			this.bookId = bundle.getString("bookId")
			if(TextUtils.isEmpty(this.bookId)){
				throw Exception("书籍id不能为空！")
			}
			//获取数据，这里在来到这个页面之前肯定会有保存操作，所以不担心获取不到数据
			book = bookService.findBookByBookId(this.bookId)
			if(book == null){
				throw Exception("获取书籍数据失败，请在书架移除本书后重新添加！")
			}
		}catch (e: Exception){
			ToastUtils.toast(e.message!!)
			finish()
		}
	}

	/**获取音量键点击翻页*/
	fun getVoicePage(): Boolean{
		return SPUtil[SPUtil.book_voice_page, false, SPUtil.SP_SYSTEM_SETUP] as Boolean
	}

	/**设置音量键点击翻页*/
	fun setVoicePage(bool: Boolean){
		this.isVoicePage = bool
		SPUtil.put(SPUtil.book_voice_page, bool, SPUtil.SP_SYSTEM_SETUP)
	}

	/**获取是否永不锁屏*/
	fun getLockScreenNever(): Boolean{
		return SPUtil[SPUtil.book_lock_screen_never, false, SPUtil.SP_SYSTEM_SETUP] as Boolean
	}

	/**设置是否永不锁屏*/
	fun setLockScreenNever(bool: Boolean){
		this.isLockScreenNever = bool
		SPUtil.put(SPUtil.book_lock_screen_never, bool, SPUtil.SP_SYSTEM_SETUP)

		//设置永不锁屏
		if(bool){
			window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
		}else{
			window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
		}
	}

	/**
	 * 填充布局
	 */
	private fun inflateLayout(){
		val root = this.layoutInflater.inflate(R.layout.view_reader, ly_reader_container)
		this.sectionView = root.findViewById(R.id.tv_section_content)
	}

	override fun onPause() {
		super.onPause()
		this.sectionView.onHide()
	}

	override fun onRestart() {
		super.onRestart()
		if(!this.bottomDialog.isShowing() && !this.sectionIndexDialog.isShowing()){
			this.sectionView.onShow()
		}
	}

	/**销毁Activity*/
	override fun onDestroy() {
		sectionView.onDestroy()
		sectionIndexDialog.onDestroy()
		bottomDialog.onDestroy()

		super.onDestroy()
	}

	/**消息的回调*/
	override fun handleMessage(msg: Message) {
		
		this.sectionView.handleMessage(msg)
		
		when(msg.what){
			//点击阅读页面的中间区域，弹出底部菜单
			Constant.handler_event_show_bottom_dialog->{
				bottomDialog.open()
			}
			//弹出章节列表弹框
			Constant.handler_event_open_section_index_dialog->{
				sectionIndexDialog.open()
			}
			//完成章节索引列表的加载的回调
			Constant.handler_event_load_book_index->{
				val list = msg.obj as List<BookIndex>
				if(list.isEmpty()){
					if(this.book!!.local){
						return
					}
					// 提示更换爬虫源
//					ToastUtils.toast("获取章节列表为空，请更换爬虫源！")
					LoadingDialogUtil.getInstance().dismiss()
					//弹框重新加载章节目录或者换源
					this.showReloadBookIndexConfirmDialog(msg)
					return
				}

				this.bookIndexList.clear()
				this.bookIndexList.addAll(list)

				//刷新列表
				sectionIndexDialog.refreshSectionList()
				
				//这里加载完消息了，得去加载章节了
				this.sectionView.initBook(this.book!!, this.bookIndexList)
			}
			//发起请求加载章节目录数据-出错
			Constant.handler_event_load_book_index_error->{
				//弹框重新加载章节目录或者换源
				this.showReloadBookIndexConfirmDialog(msg)
			}
			//发起请求加载章节数据-出错
			Constant.handler_event_load_book_section_error->{
				//弹框重新加载章节
				this.showReloadSectionConfirmDialog(msg)
			}
		}
	}


	/**显示重新加载章节列表的弹框*/
	private fun showReloadBookIndexConfirmDialog(msg: Message){
		confirmDialog.setOnConfirm2Listener("重新加载") {
			confirmDialog.dismiss()
			this.reCrawlerBookIndex()
		}
		confirmDialog.openDialog("加载章节目录错误，是否重新加载？")
	}


	/**显示重新加载章节的弹框*/
	private fun showReloadSectionConfirmDialog(msg: Message){
		val crawlerSectionVo = msg.obj as CrawlerSectionVo
		val bookIndex = crawlerSectionVo.bookIndex?:return
		confirmDialog.setOnConfirm2Listener("重新加载") {
			confirmDialog.dismiss()
			this.sectionView.loadBookSection(bookIndex.indexNum!!, bookIndex)
		}
		confirmDialog.openDialog("加载章节(${bookIndex.indexName})错误，是否重新加载？")
	}

	override fun onError(code: Int, err: ApiErrorResult) {
	}

	override fun onSuccess(result: ApiResult, code: Int) {
	}

}
